//include===================================================================
#include "RFTXSensorController.h"
#include "VirtualWire.h"

#include "MsTimer2.h"
#define FREQ 50 	// 60Hz power in these parts
#define AC_PIN 9	// Output to Opto Triac
#define LED 13		// builtin LED for testing
#define VERBOSE 1	// can has talk back?

int STATE_WAIT = 0;
int STATE_LISTEN = 1;
int STATE_READY = 2;
int MAX_ANALOG_OUTPUT = 1023;
int state;
int threshold;
double median;
unsigned long int numberSamples;
int freq; //mostres x segon
int analogInput0;
int maxAnalogInput;

const int sensorPin = A0; // pin that the sensor is attached to
//const int ledPin = 9; // pin that the LED is attached to

// variables:
int sensorValue = 0; // the sensor value
int sensorMaxValue = 750; // minimum sensor value
int sensorMinValue = 0; // maximum sensor value
volatile byte bState = 255; // controls what interrupt should be
//unsigned long int period = 100000;//milisegon
unsigned long int period = 100;//100 milisegons cada periode
unsigned long int secondsSample = 4;
unsigned long int numberTotalSample = secondsSample * (1000 / period); //el periode està en microsegons
//char sSwitch[]="switch:0";
//char sKeep[]="keepOn:0:10";
char strToSend[20] = "keepOn:0:10";

int portTXVirtualWire=2;
int numSamplesToListen=20;//això equival a 10 vegades el timeout,més o menys equival a 20 segons
int acumSamplesToListen;//els segons que romandrà encès (ara es mesura per cada 100milis equival a 1 segon encès)
int numberOutput;
int secondsOutput;

//setup========================================================================
//The setup function is called once at startup of the sketch
void setup() {
	analogInput0 = 0;
	maxAnalogInput = analogInput0;
	acumSamplesToListen=0;
	numberOutput=0;
	secondsOutput=0;


	Serial.begin(9600);
	numberSamples = 0;
	state = STATE_WAIT;
	vw_setup(4000); // Bits per sec
	vw_set_tx_pin(portTXVirtualWire);

	MsTimer2::set(period, takeNote); // 100ms period
	MsTimer2::start();
//	pinMode(4, OUTPUT);
//	digitalWrite(4, HIGH);
	threshold = -1;
	Serial.print("setup:period=1000/");
	Serial.print(period);
	Serial.println("mostres*segon");

// Add your initialization code here
}
void calculateMedian(int input) {
	if (numberSamples == numberTotalSample) {
		median = (((median * numberSamples) - (median)) + input)
				/ numberSamples;
	} else {
		numberSamples++;
		median = ((median * numberSamples) + input) / (numberSamples + 1);
	}
}
boolean isSignalUp(int input) {
	threshold = ((sensorMaxValue - median) / 2) + median;
	if (threshold < input)
		return true;
	return false;
}
boolean isSignalDown(int input) {
//	threshold=((sensorMaxValue-median)/2)+median;
	if (input < median)
		return true;
	return false;
}
void takeNote() {
//	analogInput0 = analogRead(A1);
//	Serial.print(threshold);
//	Serial.print(" ");
//	Serial.print(numberSamples);
//	Serial.print(" ");
//	Serial.print(maxAnalogInput, DEC);
//	Serial.print(" ");
//	Serial.println(median, DEC);

	if (state == STATE_WAIT && numberSamples == numberTotalSample && isSignalUp(maxAnalogInput)) {
		state = STATE_LISTEN;
	}else if (state==STATE_LISTEN && isSignalDown(maxAnalogInput)) {
		if (numSamplesToListen==acumSamplesToListen) {state=STATE_READY;}
		else {
			acumSamplesToListen++;
			Serial.println(acumSamplesToListen);
		}
	}else if (state==STATE_LISTEN && isSignalUp(maxAnalogInput)) {
		if (secondsOutput==0) secondsOutput=acumSamplesToListen;
		if (numberOutput<4) numberOutput++;

	}
	if (state == STATE_WAIT) {
//		Serial.println("TAKENOTEWAIT");
		calculateMedian(maxAnalogInput);
	}
	maxAnalogInput = 0;
}

// The loop function is called in an endless loop
void loop() {
	analogInput0 = analogRead(A1);
	if (maxAnalogInput < analogInput0)
		maxAnalogInput = analogInput0;
	if (state == STATE_LISTEN) {
//		char *msg = strToSend;
//				vw_send((uint8_t *) msg, strlen(msg));
//				vw_wait_tx();
//				state=STATE_WAIT;
//				delay(100);
	} else if (state== STATE_READY && numberOutput>0) {
		strToSend[6]=':';
		char buf[1];
		strToSend[7]=itoa((numberOutput-1), buf, 10)[0];
		strToSend[8]=':';
		char buf2[2];
		Serial.println(secondsOutput);
		strToSend[9]=itoa(secondsOutput, buf2, 10)[0];
		strToSend[10]=itoa(secondsOutput, buf2, 10)[1];
		Serial.print("SEND: ");
		Serial.println(strToSend);
		numberOutput=0;
		acumSamplesToListen=0;
		secondsOutput=acumSamplesToListen;

		char *msg = strToSend;
		vw_send((uint8_t *) msg, strlen(msg));
		vw_wait_tx();
		state=STATE_WAIT;
		delay(100);

	}
}
